<?php

namespace Viettrans\BackBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Component\HttpFoundation\Response;

/**
 * Announcement controller.
 *
 * @Route("/bo/announcement")
 */
class AnnouncementController extends Controller {
    /**
     * @Route("/", name="bo_announcement_index")
     * @Template()
     */
    public function indexAction() {
		return array();
    }

    /**
     * @Route("/delete", name="bo_announcement_delete")
     * @Template()
     */
    public function deleteAction() {
		# Get request
		$request = $this->getRequest();
		
		$id = $request->get('id');
		
		# Get entity manager object
		$em = $this->getDoctrine()->getEntityManager();
		
		# Get Repos
		$announcementRepo = $em->getRepository('ViettransFrontBundle:Announcement');
		
		$announcement = $announcementRepo->find($id);
		
		$photos = $announcement->getPhotos();
		
		if(!$announcement) return new Response('KO');

        # Begin transaction
		$em->getConnection()->beginTransaction();
		
		try {
			$em->remove($announcement);
			$em->flush();
			
			# If photo exists then delete photos
			if ($photos != NULL) {
				$photoPath = $this->container->getParameter('images_path').'/'.$photos;
				if (file_exists($photoPath)) {
					if (!unlink($photoPath)) {
						return new Response('KO');
					}
				}
			}
			
			# If there is no photo then comit transaction
			$em->getConnection()->commit();
			$em->close();
			
		} catch(\Exception $e) {
			return new Response('KO');
		}
		
		return new Response('OK');
    }
	
    /**
     * @Route("/validate", name="bo_announcement_validate")
     * @Template()
     */
    public function validateAction() {
		# Get request
		$request = $this->getRequest();
		
		$id = $request->get('id');
		
		# Get entity manager object
		$em = $this->getDoctrine()->getEntityManager();
		
		# Get Repos
		$announcementRepo = $em->getRepository('ViettransFrontBundle:Announcement');
		
		$announcement = $announcementRepo->find($id);
		
		if(!$announcement) return new Response('KO');
		
		if ($announcement->getValidatedAt()) {
			$announcement->setValidatedAt(NULL); 
		
		} else {
			$now = new \DateTime();
			$announcement->setValidatedAt($now);
		}
		
		try {
			$em->persist($announcement);
			$em->flush();
			
		} catch(\Exception $e) {
			return new Response('KO');
		}
		
		return new Response('OK');
    }
	
    /**
     * @Route("/search", name="bo_announcement_search")
     * @Template()
     */
	public function searchAction() {
		# Get request
		$request = $this->getRequest();
	
		# Get entity manager object
		$em = $this->getDoctrine()->getEntityManager();
		
		# Get Repos
		$announcementRepo = $em->getRepository('ViettransFrontBundle:Announcement');
		
		# Build query
        $qb = $em->createQueryBuilder()
                        ->select('a')
                        ->from('ViettransFrontBundle:Announcement', 'a');
						
		# By id/ids
		$id = $request->get('id');
		if (isset($id) && $id != "") {
			if (strpos($id, ',') !== false)	{
				$qb->andWhere("a.id IN ($id)");

			} else {
				$qb->andWhere("a.id = :id");
				$qb->setParameter('id', $id);
			}
		}
		
		# Order by
		$qb->orderBy('a.createdAt', 'DESC');
		
		$query = $qb->getQuery();
		
        try {
            $announcements = $query->getResult();
            
        } catch(Doctrine\ORM\NoResultException $e) {
            $announcements = array();
			
        } catch(\Exception $e) {
			$announcements = array();
		} 
		
		$totalCount = count($announcements);
		
		$activatedCount = 0;
		foreach($announcements as $announcement) {
			if ($announcement->getIsActivated()) $activatedCount++;
		}
		
		$notActivatedCount = $totalCount - $activatedCount;
		
		$infos = array(
			'total'        => $totalCount,
			'activated'    => $activatedCount,
			'notActivated' => $notActivatedCount,
		);
		
        return array(
			'announcements' => $announcements,
			'infos'         => $infos
		);
	}
}
